/**
 * @desc 解析浏览器信息
 * @param ua
 */
import moment from "moment";

export const getDevice = (ua: string) => {
  let stack = "";
  const list: string[] = [];

  for (let index = 0; index < ua.length; ) {
    const char = ua.charAt(index);
    if (char === " ") {
      if (stack.includes("(")) {
        if (stack[stack.length - 1] === ")") {
          list.push(stack);
          stack = "";
          index++;
        } else {
          index++;
          stack += char;
        }
      } else {
        list.push(stack);
        stack = "";
        index++;
      }
    } else {
      index++;
      stack += char;
    }
  }

  if (stack.length) {
    list.push(stack);
  }

  // ["Mozilla/5.0", "(iPhone; CPU iPhone OS 13_2_3 like Mac OS X)", "AppleWebKit/605.1.15", "(KHTML, like Gecko)", "Version/13.0.3", "Mobile/15E148"]

  return {
    os: list[1].replace("(", "").replace(")", ""),
    jsEngine: list[2],
    browser: list[list.length - 1]
  };
};

/**
 * @desc 时间格式化
 * @param t
 */
export function fmtDateTime(t: string) {
  if (t.includes("T")) {
    return `${t.substr(0, 10)} ${t.substr(11, 10)}`
  }
  return t;
}

/**
 * @desc 判断是否为原始对象类型
 * @param param
 */
export const isPureObject = (param: any) => {
  return param && Object.prototype.toString.call(param) === "[object Object]";
};

/**
 * @desc 格式化时间戳
 * @param t
 */
export function fmtTimeStamp(t: number) {
  return moment(t).format("YYYY-MM-DD HH:mm:ss");
}

/**
 * @desc 格式化 IP
 * @param ip
 */
export function fmtIpAddress(ip: string) {
  if (ip.includes("::ffff:")) {
    return ip.replace("::ffff:", '');
  }
  return ip;
}
